#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>

#define PORT 8080
#define BUFFER_SIZE 1024
#define ROOT_DIR "./www" // 网站根目录

void handle_client(int client_socket);
void send_response(int client_socket, int status_code, const char *status_msg, const char *content_type, const char *content);
void send_file(int client_socket, const char *file_path);

int main()
{
    int server_socket, client_socket;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_len = sizeof(client_addr);

    // 创建 socket
    if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    // 设置 socket 选项
    int opt = 1;
    if (setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)))
    {
        perror("setsockopt failed");
        exit(EXIT_FAILURE);
    }

    // 绑定地址和端口
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(PORT);

    if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
    {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    // 监听连接
    if (listen(server_socket, 5) == -1)
    {
        perror("listen failed");
        exit(EXIT_FAILURE);
    }

    printf("Server running on http://localhost:%d\n", PORT);

    // 主循环，接受客户端连接
    while (1)
    {
        client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_len);
        if (client_socket == -1)
        {
            perror("accept failed");
            continue;
        }

        printf("Connection accepted from %s:%d\n",
               inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

        handle_client(client_socket);
        close(client_socket);
    }

    close(server_socket);
    return 0;
}

void handle_client(int client_socket)
{
    char buffer[BUFFER_SIZE];
    ssize_t bytes_read;

    // 读取客户端请求
    bytes_read = read(client_socket, buffer, BUFFER_SIZE - 1);
    if (bytes_read <= 0)
    {
        perror("read failed or connection closed");
        return;
    }
    buffer[bytes_read] = '\0';

    // 简单的请求解析
    char method[16], path[256];
    sscanf(buffer, "%s %s", method, path);

    // 只处理 GET 请求
    if (strcmp(method, "GET") != 0)
    {
        send_response(client_socket, 501, "Not Implemented", "text/plain", "501 Not Implemented\n");
        return;
    }

    // 处理根路径
    if (strcmp(path, "/") == 0)
    {
        path = "/index.html";
    }

    // 构建文件路径
    char file_path[512];
    snprintf(file_path, sizeof(file_path), "%s%s", ROOT_DIR, path);

    // 检查文件是否存在
    if (access(file_path, F_OK) == -1)
    {
        send_response(client_socket, 404, "Not Found", "text/plain", "404 Not Found\n");
        return;
    }

    // 发送文件
    send_file(client_socket, file_path);
}

void send_response(int client_socket, int status_code, const char *status_msg, const char *content_type, const char *content)
{
    char response[BUFFER_SIZE];
    int length = snprintf(response, BUFFER_SIZE,
                          "HTTP/1.1 %d %s\r\n"
                          "Content-Type: %s\r\n"
                          "Content-Length: %zu\r\n"
                          "Connection: close\r\n"
                          "\r\n"
                          "%s",
                          status_code, status_msg,
                          content_type,
                          strlen(content),
                          content);
    write(client_socket, response, length);
}

void send_file(int client_socket, const char *file_path)
{
    FILE *file = fopen(file_path, "rb");
    if (!file)
    {
        send_response(client_socket, 500, "Internal Server Error", "text/plain", "500 Internal Server Error\n");
        return;
    }

    // 获取文件大小
    fseek(file, 0, SEEK_END);
    long file_size = ftell(file);
    fseek(file, 0, SEEK_SET);

    // 发送响应头
    char header[BUFFER_SIZE];
    const char *content_type = "text/html"; // 简单起见，假设所有文件都是HTML
    int header_length = snprintf(header, BUFFER_SIZE,
                                 "HTTP/1.1 200 OK\r\n"
                                 "Content-Type: %s\r\n"
                                 "Content-Length: %ld\r\n"
                                 "Connection: close\r\n"
                                 "\r\n",
                                 content_type, file_size);
    write(client_socket, header, header_length);

    // 发送文件内容
    char buffer[BUFFER_SIZE];
    size_t bytes_read;
    while ((bytes_read = fread(buffer, 1, BUFFER_SIZE, file)) > 0)
    {
        write(client_socket, buffer, bytes_read);
    }

    fclose(file);
}